/* Connect javascript and presentation layer */
function search_survey_by_program_and_major(keyword, program, major)
{
	var program_id, major_id, search_keyword;
    search_keyword = keyword;
	program_id = program;
	major_id = major;
    $('#surveyList').html("<table class=generalbox border=1 align=center style=\"margin-left:16%;\"><tr><td><h1>PROCESSING</h1></td></tr></table>");
	//search_keyword = $("#id_txtKeyword").val();
	//program_id = $("#id_ddlProgram").val();
	//major_id = $("#id_ddlMajor").val();
    
	$.ajax({
		  type: 'GET',
		  url: "../ajax.php?tim=survey&keyword="+keyword+"&program="+program_id+"&major="+major_id,
		  data:'',
		  dataType: 'html',
		  success: function(msg){
			  $('#surveyList').html(msg);
		  },
	});
} 

//Dùng trong trang clone_survey.php => hiện major của 1 program
function filter_survey_by_program_and_major(keyword, program, major)
{
	var program_id, major_id, search_keyword;
    search_keyword = keyword;
	program_id = program;
	major_id = major;
    $('#surveyList').html("<table class=generalbox border=1 align=center style=\"margin-left:16%;\"><tr><td><h1>PROCESSING</h1></td></tr></table>");
	//search_keyword = $("#id_txtKeyword").val();
	//program_id = $("#id_ddlProgram").val();
	//major_id = $("#id_ddlMajor").val();
    
	$.ajax({
		  type: 'GET',
		  url: "../ajax.php?tim=filter_survey&keyword="+keyword+"&program="+program_id+"&major="+major_id,
		  data:'',
		  dataType: 'html',
		  success: function(msg){
			  $('#surveyList').html(msg);
		  },
	});
}

//Dùng trong trang add_survey.php => hiện major của 1 program
function showMajorsByProgram(program_id){
    $.ajax({
		  type: 'GET',
		  url: "../ajax.php?tim=majorbyprogram&keyword=&program="+program_id+"&major=",
		  data:'',
		  dataType: 'html',
		  success: function(msg){
                var data = jQuery.parseJSON(msg);
                $('#majorList').html('');
                var strOutput = '';
                $.each(data, function(key, value) {
                    strOutput += '<input type="checkbox" checked="checked" id="majors" name="majors" value="'+value.id+'"> '+value.major_name + '</br>';
                });
                $('#majorList').append(strOutput);
		  },
	});
}

function getMaxDepthLo(program_id){
    $.ajax({
		  type: 'GET',
		  url: "../ajax.php?tim=maxLevOfProgram&keyword=&program="+program_id+"&major=",
		  data:'',
		  dataType: 'html',
		  success: function(msg){
		      var dropdown = $('#id_ddlDepthLo');
		      dropdown.html("");
		      maxLev = parseInt(msg);
              outputStr = "";
		      for(i = 1; i <= maxLev; i++){
		          outputStr += '<option value='+i+'>'+i+'</option>';		          
		      }
              dropdown.html(outputStr);
		  },
	});
}

//Dùng trong trang surveymanagement.php => extend survey
function extendSurvey(survey,key){
    var days = document.getElementById("extend"+survey).value;
    $.ajax({
		  type: 'GET',
		  url: "extendSurvey.php?numb="+survey+"&days="+days+"&key="+key,
		  data:'',
		  dataType: 'html',
		  success: function(msg){
		      var keyword = $('#id_txtKeyword').val();
              var program = $('#id_ddlProgram').val();
              var major = $('#id_ddlMajor').val();
                search_survey_by_program_and_major(keyword,program,major);
		  },
	});
}

function clone_survey(survey){
    $('#selected_survey').val(survey);
    $('#mform1').submit();
}

function delete_survey(message,title,survey,key){
    var decision = confirm(message+title);
    if(decision == true){
        $.ajax({
    		  type: 'GET',
    		  url: "deleteSurvey.php?numb="+survey+"&key="+key,
    		  data:'',
    		  dataType: 'html',
    		  success: function(msg){
    		      var keyword = $('#id_txtKeyword').val();
                  var program = $('#id_ddlProgram').val();
                  var major = $('#id_ddlMajor').val();
                    search_survey_by_program_and_major(keyword,program,major);
    		  },
    	});
    }
}
//used in notification.php
function display_surveys_of_teacher(user_id){
    $('#surveyList').html("<table class=generalbox border=1 align=center style=\"margin-left:16%;\"><tr><td><h1>PROCESSING</h1></td></tr></table>");
    $.ajax({
		  type: 'GET',
		  url: "../ajax.php?tim=surveyTeacher&keyword="+user_id+"&program=&major=",
		  data:'',
		  dataType: 'html',
		  success: function(msg){
			  $('#surveyList').html(msg);
		  },
	});    
}

//used in notification.php
function retake_survey(user_id){
        
}

function preview_survey_before_add(){
    try{var myValidator = validate_form_add_survey;} 
    catch(e){alert("Invalid Requirement Checking Process. Code:453");return true;} 
    var result = myValidator(this);
    if(!result){
        return myValidator(this);    
    }else{
        var w = window.open("preview_survey.php");
        w.document.writeln('<script src="../js/jquery-1.8.3.min.js"></script>');
        w.document.writeln("<div id=\"loading\"><center><image src='../css/images/ajax-loader.gif'/></center></div>");
        
        getCheckboxValue('selected_major','majors');
        getValueOfUnorderedList('selected_question','sortable2');
        
        var title = $("#id_txtSurveyTitle").val();var program = $("#id_ddlProgram").val();var majors = $("#selected_major").val();
        var questions = $("#selected_question").val();
        var depth = $("#id_ddlDepthLo").val();
        var day = $("#id_expireDateTime_day").val();var month = $("#id_expireDateTime_month").val();var year = $("#id_expireDateTime_year").val();
        var hour = $("#id_expireDateTime_hour").val();var minute =  $("#id_expireDateTime_minute").val();
        var titleSum = $("#id_txtTitleOfSummary").val();
        var titleQuestion = $("#id_txtTitleOfQuestion").val();
        var titleLo = $("#id_txtTitleOfLO").val();
        
        var Sum = tinyMCE.get('id_txtAreaSummary').getContent();
        var questionSum = tinyMCE.get('id_txtAreaQuestion').getContent();        
        var LoSum = tinyMCE.get('id_txtAreaLO').getContent();
        
        var curKey = $("input[name='sesskey']").val();
//        alert("title:"+title+"-"+"program:"+program+"-"+"major:"+majors+"-"+"questions:"+questions
//                +"-"+"depth:"+depth+"-"+"day:"+day+"-"+"month:"+month+"-"+"year:"+year
//                +"-"+"hour:"+hour+"-"+"minute:"+minute+"-"+"titleSum:"+titleSum+"-"+"sum:"+Sum);
        var previewSurvey = new Preview_Survey(title, program, majors, questions, depth, 
                                                year+"-"+month+"-"+day+" "+hour+":"+minute+":00", 
                                                titleSum, Sum, titleQuestion, questionSum, titleLo, LoSum, curKey); 
        $.ajax({
    		  type: 'POST',
    		  url: "preview_survey.php",
    		  data: previewSurvey,
    		  dataType: 'html',
    		  success: function(msg){
                    w.document.writeln("<script>$('#loading').html('');</script>");
                    w.document.writeln(msg);
    		  },
	    }); 
    }    
}

function preview_survey_before_update(){
    try{var myValidator = validate_form_edit_survey;} 
    catch(e){alert("Invalid Requirement Checking Process. Code:453");return true;} 
    var result = myValidator(this);
    if(!result){
        return myValidator(this);    
    }else{
        var w = window.open("preview_survey.php");
        w.document.writeln('<script src="../js/jquery-1.8.3.min.js"></script>');
        w.document.writeln("<div id=\"loading\"><center><image src='../css/images/ajax-loader.gif'/></center></div>");
        
        getCheckboxValue('selected_major','majors');
        getValueOfUnorderedList('selected_question','sortable2');
        
        var title = $("#id_txtSurveyTitle").val();var program = $("#id_ddlProgram").val();var majors = $("#selected_major").val();
        var questions = $("#selected_question").val();
        var depth = $("#id_ddlDepthLo").val();
        var day = $("#id_expireDateTime_day").val();var month = $("#id_expireDateTime_month").val();var year = $("#id_expireDateTime_year").val();
        var hour = $("#id_expireDateTime_hour").val();var minute =  $("#id_expireDateTime_minute").val();
        var titleSum = $("#id_txtTitleOfSummary").val();
        var titleQuestion = $("#id_txtTitleOfQuestion").val();
        var titleLo = $("#id_txtTitleOfLO").val();
        
        var Sum = tinyMCE.get('id_txtAreaSummary').getContent();
        var questionSum = tinyMCE.get('id_txtAreaQuestion').getContent();        
        var LoSum = tinyMCE.get('id_txtAreaLO').getContent();
        
        var curKey = $("input[name='sesskey']").val();
//        alert("title:"+title+"-"+"program:"+program+"-"+"major:"+majors+"-"+"questions:"+questions
//                +"-"+"depth:"+depth+"-"+"day:"+day+"-"+"month:"+month+"-"+"year:"+year
//                +"-"+"hour:"+hour+"-"+"minute:"+minute+"-"+"titleSum:"+titleSum+"-"+"sum:"+Sum);
        var previewSurvey = new Preview_Survey(title, program, majors, questions, depth, 
                                                year+"-"+month+"-"+day+" "+hour+":"+minute+":00", 
                                                titleSum, Sum, titleQuestion, questionSum, titleLo, LoSum, curKey); 
        $.ajax({
    		  type: 'POST',
    		  url: "preview_survey.php",
    		  data: previewSurvey,
    		  dataType: 'html',
    		  success: function(msg){
                    w.document.writeln("<script>$('#loading').html('');</script>");
                    w.document.writeln(msg);
    		  },
	    }); 
    }    
}

function save_assessment_teaching_method_of_lo(sts_id, lo_id, content){
        var assessAndTeachMethod = new AssessAndTeach(sts_id,lo_id,content);
        
        $.ajax({
    		  type: 'POST',
    		  url: "../ajaxDoSurvey.php?do=assess",
    		  data: assessAndTeachMethod,
    		  dataType: 'html',
    		  success: function(msg){
    		      $('#assessmentLO_block_'+lo_id).css({"color":"green"});
    		  },
	    }); 
}

function save_itu_value(sts_id, lo_id, content, typeOfValue){
        var ituVal = new ITUValue(sts_id,lo_id,content,typeOfValue);
        $.ajax({
    		  type: 'POST',
    		  url: "../ajaxDoSurvey.php?do=check",
    		  data: ituVal,
    		  dataType: 'html',
    		  success: function(msg){
    		      
    		  },
	    });
}

function save_answer(sts_id, question_id, typeOfQuestion){
    if(typeOfQuestion == 1){
        var input = $('#question_'+question_id).val();
        var ans = new AnswerOfQuestion(sts_id, question_id, input, typeOfQuestion);
        $.ajax({
    		  type: 'POST',
    		  url: "../ajaxDoSurvey.php?do=answer",
    		  data: ans,
    		  dataType: 'html',
    		  success: function(msg){
    		      $('#question_'+question_id).css({'background-color':'33FF99'});
    		  },
	    });
    }else if(typeOfQuestion == 2){
        $('div[id*="div_1_question_"]').css({'color':'black'})
        var input = $('#question_'+question_id+":checked").val();
        var ans = new AnswerOfQuestion(sts_id, question_id, input, typeOfQuestion);
        $.ajax({
    		  type: 'POST',
    		  url: "../ajaxDoSurvey.php?do=answer",
    		  data: ans,
    		  dataType: 'html',
    		  success: function(msg){
    		      $('#div_1_question_'+question_id+"_"+input).css({'color':'green'});
    		  },
	    });
    }else if(typeOfQuestion == 4){
        $('div[id*="div_4_question_"]').css({'color':'black'})
        var input = $('#question_'+question_id+":checked").val();
        var ans = new AnswerOfQuestion(sts_id, question_id, input, typeOfQuestion);
        $.ajax({
    		  type: 'POST',
    		  url: "../ajaxDoSurvey.php?do=answer",
    		  data: ans,
    		  dataType: 'html',
    		  success: function(msg){
    		      $('#div_4_question_'+question_id+"_"+input).css({'color':'green'});
    		  },
	    });
    }
}

function save_answer_of_checkbox(sts_id, question_id, answer_id, state){
        var state = $('#question_'+question_id+"_"+answer_id).is(':checked');
        var ans = new AnswerOfQuestion(sts_id, question_id, answer_id, 3);
        if(state){
            $.ajax({
    		  type: 'POST',
    		  url: "../ajaxDoSurvey.php?do=answer&state=1",
    		  data: ans,
    		  dataType: 'html',
    		  success: function(msg){
    		      $('#div_3_question_'+question_id+"_"+answer_id).css({'color':'green'});
    		  },
	       });
        }else{
            $.ajax({
    		  type: 'POST',
    		  url: "../ajaxDoSurvey.php?do=answer&state=0",
    		  data: ans,
    		  dataType: 'html',
    		  success: function(msg){
    		      $('#div_3_question_'+question_id+"_"+answer_id).css({'color':'green'});
    		  },
	    });
        }
}
/////////////////////USE FOR QUESTION MANAGEMENT//////////////////////////////////
function showTypeofQuestion(questiontype)
{
  
    if (questiontype=='0')
    {
        $('#addquestionbutton').hide();
        $('#plainText').hide();
        $('#dropdownList').hide();
        $('#checkBox').hide();
        $('#Scale').hide();
  
    }
      
    if (questiontype=='1')
    {
        
        $('#plainText').show();
        $('#dropdownList').hide();
        $('#checkBox').hide();
        $('#Scale').hide();
        $('#addquestionbutton').show();

    }
      
    if (questiontype=='2')
    {
        $('#plainText').hide();
        $('#dropdownList').show();
        $('#checkBox').hide();
        $('#Scale').hide();
        $('#addquestionbutton').show();
    }  
    
    if (questiontype=='3')
    {
        $('#plainText').hide();
        $('#dropdownList').hide();
        $('#checkBox').show();
        $('#Scale').hide();
        $('#addquestionbutton').show();
    }
    
    if (questiontype=='4')
    {
        $('#Scale').show();
        $('#plainText').hide();
        $('#dropdownList').hide();
        $('#checkBox').hide();
        $('#addquestionbutton').show();
    }
    //Set null for plaintext and hide submit button when change another type
    $("#id_plaintext_qt").val(null);
    $('#plaintextwarning').text('');
    document.getElementById("id_submitbutton").disabled= true;
    
    //Set null for dropdown list and hide submit button when change another type 
    $('#id_dropdown_qt').val(null);
    $('#id_dropdown_ans').val(null);
    $('#ddlwarning').text('');
    $('#addqtbuttonwarning').text('');
    var drop_ans = document.getElementById('select_ddl_answer');
    var i;
         
            for (i = drop_ans.length-1; i>=0; i--) {
             drop_ans.remove(i);
            }
    //DDl answer options        
    document.getElementById("id_editoptionbutton").disabled= true;
    $('#editoptionwarning').text('');
    
    //Set null for checkbox list and hide submit button when change another type
    $('#id_checkbox_qt').val(null);
    $('#id_checkbox_ans').val(null);
    $('#cbxwarning').text('');
    $('#cbxanswarning').text('');
    var cbx_ans = document.getElementById('select_cbx_answer');
    var i;
         
            for (i = cbx_ans.length-1; i>=0; i--) {
             cbx_ans.remove(i);
            }
    //CBX answer options        
    document.getElementById("id_editcbxoptionbutton").disabled= true;
    $('#editcbxoptionwarning').text('');
    
    //Set null for scale list and hide submit button when change another type
    $("#id_scale_qt").val(null);
    $('#scalewarning').text('');
    
}
function add_answer_down(checktype)
{
    
    if(checktype=='ddl')
    {
    drop_ans = document.getElementById('select_ddl_answer');
    add_answer = document.getElementById('id_dropdown_ans');
    dropdown_answer = $('#id_dropdown_ans').val();

    temp=document.createElement('option');
    temp.title = dropdown_answer;
    temp.text = dropdown_answer;
    temp.value = dropdown_answer;
    drop_ans.add(temp,null);
    add_answer.value='';
    var temp = $('#id_ddl_temp').val() + '#' +temp.value + "#";         
    $('#id_ddl_temp').val(temp);
    }
    else if(checktype == 'cbx')
    {
    cbx_ans = document.getElementById('select_cbx_answer');
    add_answer = document.getElementById('id_checkbox_ans');
    checkbox_answer = $('#id_checkbox_ans').val();

    temp=document.createElement('option');
    temp.title = checkbox_answer;
    temp.text = checkbox_answer;
    temp.value = checkbox_answer;
    cbx_ans.add(temp,null);
    add_answer.value='';
    var temp = $('#id_cbx_temp').val() + '#' +temp.value + "#";         
    $('#id_cbx_temp').val(temp);
    }
    
    
}
function answer_del(checktype)
{
    if(checktype=='ddl')
    {
         var drop_ans = document.getElementById('select_ddl_answer');
         var i;
         
         for (i = drop_ans.length-1; i>=0; i--) {
            if (drop_ans.options[i].selected) {
             
             
            var temp = $('#id_ddl_temp').val();
            
            var replace_str = '#'+ drop_ans.options[i].value+'#';
             var xxx = temp.replace(replace_str, '');
             $('#id_ddl_temp').val(xxx);
             
             drop_ans.remove(i);
            }
        }
    }
    else if(checktype=='cbx')
    {
         var cbx_ans = document.getElementById('select_cbx_answer');
         var i;
        
         for (i = cbx_ans.length-1; i>=0; i--) {
            if (cbx_ans.options[i].selected) {
             
             
            var temp = $('#id_cbx_temp').val();
            var replace_str = '#'+ cbx_ans.options[i].value+'#';
             var xxx = temp.replace(replace_str, '');
             $('#id_cbx_temp').val(xxx);
             cbx_ans.remove(i);
            }
        }
        
    }
}
function answer_up(checktype)
{
    if(checktype =='ddl')
    {
    
      $('#select_ddl_answer option:selected').each(function(){
      
      var temp = $('#id_ddl_temp').val();
      
      var replace_str = '#'+ $(this).val()+'#';
      var replace_str_2 = '#'+ $(this).prev().val()+'#';
//      alert(replace_str);
//      alert(replace_str_2);
      var xxx = replace_str_2 + replace_str;
       //alert(xxx);
      var yyy = replace_str + replace_str_2;
      //alert(yyy);
      var zzz = temp.replace(xxx,yyy);
      //alert(zzz);
      $('#id_ddl_temp').val(zzz);
      $(this).insertBefore($(this).prev());
      });
    
    }  
    else if(checktype =='cbx')  
    {
        $('#select_cbx_answer option:selected').each(function(){
      
      var temp = $('#id_cbx_temp').val();
      var replace_str = '#'+ $(this).val()+'#';
      var replace_str_2 = '#'+ $(this).prev().val()+'#';
      
      var xxx = replace_str_2 + replace_str;
      var yyy = replace_str + replace_str_2;
      var zzz = temp.replace(xxx,yyy);
      $('#id_cbx_temp').val(zzz);
      $(this).insertBefore($(this).prev());
      });
        
    }  
      
}
function answer_down(checktype)
{
        if(checktype =='ddl')
         {
        
        var drop_ans = document.getElementById('select_ddl_answer');
        for (i = drop_ans.length-1; i>=0; i--) {
        if (drop_ans.options[i].selected) {
            
            var temp = $(drop_ans.options[i]);
            
            var replace_str = '#'+ temp.val()+'#';
            var replace_str_2 = '#'+ temp.next().val()+'#';
            
            var temp2 = $('#id_ddl_temp').val();
            var xxx = replace_str + replace_str_2;
            var yyy = replace_str_2 + replace_str;
            var zzz = temp2.replace(xxx,yyy);
            $('#id_ddl_temp').val(zzz);
      
            temp.insertAfter(temp.next());
            }
        }
        }
        else if (checktype =='cbx')
        {
            var cbx_ans = document.getElementById('select_cbx_answer');
            for (i = cbx_ans.length-1; i>=0; i--) {
            if (cbx_ans.options[i].selected) {
            
            var temp = $(cbx_ans.options[i]);
            
            var replace_str = '#'+ temp.val()+'#';
            var replace_str_2 = '#'+ temp.next().val()+'#';
            
            var temp2 = $('#id_cbx_temp').val();
            var xxx = replace_str + replace_str_2;
            var yyy = replace_str_2 + replace_str;
            var zzz = temp2.replace(xxx,yyy);
            $('#id_cbx_temp').val(zzz);
      
            temp.insertAfter(temp.next());
            }
            }   
        
    
        }        
      
}
function onfocus_checknull(checktype)
{
    //Plaintext
    if(checktype=='pt'){
    document.getElementById("id_submitbutton").disabled= false;
    $('#plaintextwarning').text('');
    }
    //Scale
    if(checktype=='scale'){
    document.getElementById("id_submitbutton").disabled= false;
    $('#scalewarning').text('');
    }
    //Dropdown list
    if(checktype=='ddl' || checktype=='ddlans'){
    if(checktype == 'ddl')
    document.getElementById("id_submitbutton").disabled= false;
    $('#ddlwarning').text('');
    document.getElementById("addqtbutton").disabled= false;
    $('#addqtbuttonwarning').text('');
    }
    //Dropdown list options
    if(checktype =='ddloption')
    {
        document.getElementById("id_editoptionbutton").disabled= false;
        $('#editoptionwarning').text('');
    }
    
    // Checkbox
    if(checktype=='cbx' || checktype=='cbxans'){
    if(checktype == 'cbx')
    document.getElementById("id_submitbutton").disabled= false;
    $('#cbxwarning').text('');
    document.getElementById("addcbxbutton").disabled= false;
    $('#cbxanswarning').text('');
    }
    
    if(checktype=='cbxoption')
    {
    document.getElementById("id_editcbxoptionbutton").disabled= false;
    $('#editcbxoptionwarning').text('');
    }
}
function onblur_checknull(checktype,curlang)
{
    //Plain text
   if(checktype == 'pt')
   {
    pt_textarea = document.getElementById('id_plaintext_qt');
    if(pt_textarea.value == ''){
    document.getElementById("id_submitbutton").disabled= true;
    if(curlang=='en' || curlang== '')
    $('#plaintextwarning').append('Please fill your question');
    else
    $('#plaintextwarning').append('Xin hãy điền câu hỏi');
    }
    else{
            count = 0;
            n = pt_textarea.value.length;
            for(i=0;i<n;i++){
                
                if(pt_textarea.value[i]== ' '|| pt_textarea.value[i]=='\n')
                count++;
            
            }
            if(count == n)
            {
                document.getElementById("id_submitbutton").disabled= true;
                if(curlang=='en' || curlang== '')
                $('#plaintextwarning').append('You must fill at least one character (not space)');
                else
                $('#plaintextwarning').append('Bạn phải nhập ít nhất 1 kí tự khác khoảng trắng');
            }
    }
   }
   // Dropdown list
   if(checktype == 'ddl'|| checktype =='ddlans')
        {
     if(checktype == 'ddl'){
        
        ddl_textarea = document.getElementById('id_dropdown_qt');
        ddl_select = document.getElementById('select_ddl_answer');
        if(ddl_select.length ==0)
        document.getElementById("id_submitbutton").disabled= true;
        
        if(ddl_textarea.value == ''){
            
        if(curlang=='en' || curlang== '')
        $('#ddlwarning').append('Please fill your question');
        else
        $('#ddlwarning').append('Xin hãy điền câu hỏi');  
         
            document.getElementById("addqtbutton").disabled= true;
            document.getElementById("id_submitbutton").disabled= true;
            }
            else{
                 count = 0;
                n = ddl_textarea.value.length;
                for(i=0;i<n;i++){
                    
                    if(ddl_textarea.value[i]== ' '|| ddl_textarea.value[i]=='\n')
                    count++;
                
                }
                if(count == n)
                {
                    document.getElementById("addqtbutton").disabled= true;
                    document.getElementById("id_submitbutton").disabled= true;
                    if(curlang=='en' || curlang== '')
                    $('#ddlwarning').append('You must fill at least one character (not space)');
                    else
                    $('#ddlwarning').append('Bạn phải nhập ít nhất 1 kí tự khác khoảng trắng');
                }
            }
         }
         
         if(checktype == 'ddlans'){
            
            ddl_answer = document.getElementById('id_dropdown_ans');
            if(ddl_answer.value == ''){
            if(curlang=='en' || curlang== '')
            $('#addqtbuttonwarning').append('Please fill your answer');
            else
            $('#addqtbuttonwarning').append('Xin hãy điền trả lời');
            
            document.getElementById("addqtbutton").disabled= true;
            }
            else{
                count = 0;
                temp =0;
                n = ddl_answer.value.length;
                for(i=0;i<n;i++){
                    
                    if(ddl_answer.value[i]== ' '|| ddl_answer.value[i]=='\n')
                    count++;
                    if(ddl_answer.value[i]=='#')
                    temp++;
                
                }
                if(count == n)
                {
                    document.getElementById("addqtbutton").disabled= true;
                    if(curlang=='en' || curlang== '')
                    $('#addqtbuttonwarning').append('You must fill at least one character(not space)');
                    else
                    $('#addqtbuttonwarning').append('Bạn phải nhập ít nhất 1 kí tự khác khoảng trắng');
                }
                if(temp != 0){
                    document.getElementById("addqtbutton").disabled= true;
                    if(curlang=='en' || curlang== '')
                    $('#addqtbuttonwarning').append('You cannot use # in your answer');
                    else
                    $('#addqtbuttonwarning').append('Bạn không dùng kí tự # trong câu trả lời');
                }
                
            }
         }
       }
   
   //Checkbox
     if(checktype == 'cbx'|| checktype =='cbxans')
     {
     if(checktype == 'cbx'){
        
        cbx_textarea = document.getElementById('id_checkbox_qt');
        cbx_select = document.getElementById('select_cbx_answer');
        
        if(cbx_select.length ==0)
        document.getElementById("id_submitbutton").disabled= true;
        
        if(cbx_textarea.value == ''){
        if(curlang=='en' || curlang== '')
        $('#cbxwarning').append('Please fill your question');
        else
        $('#cbxwarning').append('Xin hãy điền câu hỏi');
           
            document.getElementById("addcbxbutton").disabled= true;
            document.getElementById("id_submitbutton").disabled= true;
            }
            else{
                 count = 0;
                n = cbx_textarea.value.length;
                for(i=0;i<n;i++){
                    
                    if(cbx_textarea.value[i]== ' '|| cbx_textarea.value[i]=='\n')
                    count++;
                
                }
                if(count == n)
                {
                    document.getElementById("addcbxbutton").disabled= true;
                    document.getElementById("id_submitbutton").disabled= true;
                    if(curlang=='en' || curlang== '')
                    $('#cbxwarning').append('You must fill at least one character(not space)');
                    else
                    $('#cbxwarning').append('Bạn phải nhập ít nhật 1 kí tự khác khoảng trắng');
                }
            }
         }
         
         if(checktype == 'cbxans'){
            
            cbx_answer = document.getElementById('id_checkbox_ans');
            
            if(cbx_answer.value == ''){
            if(curlang=='en' || curlang== '')
            $('#cbxanswarning').append('Please fill your answer');
            else
            $('#cbxanswarning').append('Xin hãy điền trả lời');
            document.getElementById("addcbxbutton").disabled= true;
            }
            else{
                count = 0;
                temp =0;
                n = cbx_answer.value.length;
                for(i=0;i<n;i++){
                    
                    if(cbx_answer.value[i]== ' '|| cbx_answer.value[i]=='\n')
                    count++;
                    if(cbx_answer.value[i]=='#')
                    temp++;
                
                }
                if(count == n)
                {
                    document.getElementById("addcbxbutton").disabled= true;
                    if(curlang=='en' || curlang== '')
                    $('#cbxanswarning').append('You must fill at least one character(not space)');
                    else
                    $('#cbxanswarning').append('Bạn phải nhập ít nhất 1 kí tự khác khoảng trắng');
                }
                if(temp != 0){
                    document.getElementById("addcbxbutton").disabled= true;
                    if(curlang=='en' || curlang== '')
                    $('#cbxanswarning').append('You cannot use # in your answer');
                    else
                    $('#cbxanswarning').append('Bạn không dùng kí tự # trong câu trả lời');
                }
                
            }
         }
     }
    
    //Scale
   if(checktype == 'scale')
   {
    scale_textarea = document.getElementById('id_scale_qt');
    if(scale_textarea.value == ''){
    document.getElementById("id_submitbutton").disabled= true;
    if(curlang=='en' || curlang== '')
    $('#scalewarning').append('Please fill your question');
    else
    $('#scalewarning').append('Xin hãy điền câu hỏi');
    }
    else{
            count = 0;
            n = scale_textarea.value.length;
            for(i=0;i<n;i++){
                
                if(scale_textarea.value[i]== ' '|| scale_textarea.value[i]=='\n')
                count++;
            
            }
            if(count == n)
            {
                document.getElementById("id_submitbutton").disabled= true;
                if(curlang=='en' || curlang== '')
                $('#scalewarning').append('You must fill at least one character(not space)');
                else
                $('#scalewarning').append('Bạn phải nhập ít nhất 1 kí tự khác khoảng trắng');
            }
    }
   }
   //check ddl options
   if(checktype == 'ddloption') 
   {
    ddl_option_textarea = document.getElementById('id_edit_ddl_option');

    if(ddl_option_textarea.value == ''){
    document.getElementById("id_editoptionbutton").disabled= true;
    if(curlang=='en' || curlang== '')
    $('#editoptionwarning').append('Please fill your options');
    else
    $('#editoptionwarning').append('Xin hãy điền trả lời');
    }
    else{
                count = 0;
                temp =0;
                n = ddl_option_textarea.value.length;
                for(i=0;i<n;i++){
                    
                    if(ddl_option_textarea.value[i]== ' '|| ddl_option_textarea.value[i]=='\n')
                    count++;
                    if(ddl_option_textarea.value[i]=='#')
                    temp++;
                
                }
                if(count == n)
                {
                    document.getElementById("id_editoptionbutton").disabled= true;
                    if(curlang=='en' || curlang== '')
                    $('#editoptionwarning').append('You must fill at least one character(not space)');
                    else
                    $('#editoptionwarning').append('Bạn phải nhập ít nhất 1 kí tự khác khoảng trắng');
                }
                if(temp != 0){
                    document.getElementById("id_editoptionbutton").disabled= true;
                    if(curlang=='en' || curlang== '')
                    $('#editoptionwarning').append('You cannot use # in your answer');
                    else
                    $('#editoptionwarning').append('Bạn không dùng kí tự # trong câu trả lời');
                }
    }
   }
   if (checktype == 'cbxoption')
   {
    cbx_option_textarea = document.getElementById('id_edit_cbx_option');

    if(cbx_option_textarea.value == ''){
    document.getElementById("id_editcbxoptionbutton").disabled= true;
    if(curlang=='en' || curlang== '')
    $('#editcbxoptionwarning').append('Please fill your options');
    else
    $('#editcbxoptionwarning').append('Xin hãy điền trả lời');
    }
    else{
                count = 0;
                temp =0;
                n = cbx_option_textarea.value.length;
                for(i=0;i<n;i++){
                    
                    if(cbx_option_textarea.value[i]== ' '|| cbx_option_textarea.value[i]=='\n')
                    count++;
                    if(cbx_option_textarea.value[i]=='#')
                    temp++;
                
                }
                if(count == n)
                {
                    document.getElementById("id_editcbxoptionbutton").disabled= true;
                    if(curlang=='en' || curlang== '')
                    $('#editcbxoptionwarning').append('You must fill at least one character(not space)');
                    else
                    $('#editcbxoptionwarning').append('Bạn phải nhập ít nhất 1 kí tự khác khoảng trắng');
                }
                if(temp != 0){
                    document.getElementById("id_editoptionbutton").disabled= true;
                    if(curlang=='en' || curlang== '')
                    $('#editcbxoptionwarning').append('You cannot use # in your answer');
                    else
                    $('#editcbxoptionwarning').append('Bạn không dùng kí tự # trong câu trả lời');
                }
    }
   }
}
function showaddquestionbutton(){

 return document.getElementById("id_submitbutton").disabled= false;
}
function setoptiontitle_automatic()
{
//set title for dropdown list option
    ddl_options=document.getElementById('select_ddl_answer');
    n = ddl_options.length;
    //alert(n);
    for(i=0;i<n;i++)
    {
    anstitle = ddl_options.options[i].text;
    //alert(anstitle);
    ddl_options.options[i].title = anstitle;
    }
    
// set title for checkbox options

 cbx_options=document.getElementById('select_cbx_answer');
 n = cbx_options.length;
    //alert(n);
    for(i=0;i<n;i++)
        {
        anstitle = cbx_options.options[i].text;

        cbx_options.options[i].title = anstitle;
    }
    
  

}
function optiontext(checktype)
{
    //Set value for textare options
    if(checktype == 'ddl')
    {
     $('#select_ddl_answer option:selected').each(function(){
        textvalue = $(this).val();
        $('#id_edit_ddl_option').val(textvalue);
        });
     }
     
     if(checktype == 'cbx')
     {
     $('#select_cbx_answer option:selected').each(function(){
        textvalue = $(this).val();
        $('#id_edit_cbx_option').val(textvalue);
        });
     }

 
}

function edit_optiontext(checktype)
{
    if(checktype =='ddl')
    {
    answer = $('#id_edit_ddl_option').val();
    ddl = document.getElementById('select_ddl_answer');
    temp = $('#id_ddl_temp').val();
    
    for(i=0;i<ddl.length;i++)
    {
        if(ddl.options[i].selected == true)
        {
            var string_2= '#'+ ddl.options[i].text +'#';
            ddl.options[i].value = answer;
            ddl.options[i].text = answer;
            ddl.options[i].title = answer;
            //Edit the text field for submitting
                var string_1 = '#'+ answer +'#';
 
                var xxx = temp.replace(string_2,string_1);
                //alert(xxx);
                $('#id_ddl_temp').val(xxx);
        }
    }
    }
    if(checktype =='cbx')
    {
    answer = $('#id_edit_cbx_option').val();
    cbx = document.getElementById('select_cbx_answer');
    //alert(answer);
    temp = $('#id_cbx_temp').val();
    
    for(i=0;i<cbx.length;i++)
    {
        if(cbx.options[i].selected == true)
        {
            var string_2= '#'+ cbx.options[i].text +'#';
            cbx.options[i].value = answer;
            cbx.options[i].text = answer;
            cbx.options[i].title = answer;
            //Edit the text field for submitting
                var string_1 = '#'+ answer +'#';
 
                var xxx = temp.replace(string_2,string_1);
                //alert(xxx);
                $('#id_cbx_temp').val(xxx);
        }
    }
    }
}
//function checkvalue(checktype)
//{
//    
//      if(checktype == 'ddl'){
//        
//        ddl_textarea = document.getElementById('id_dropdown_qt');
//        if(ddl_textarea.value == ''){
//        document.getElementById("id_submitbutton").disabled= true;
//        }
//        else{
//             count = 0;
//            n = ddl_textarea.value.length;
//            for(i=0;i<n;i++){
//                
//                if(ddl_textarea.value[i]== ' '|| ddl_textarea.value[i]=='\n')
//                count++;
//            
//            }
//            if(count == n)
//            {
//                document.getElementById("id_submitbutton").disabled= true;
//            }
//        }
//     }
//    
//}

//    if(documentvalue==''){
//        document.getElementById("id_submitbutton").disabled= true;
//        if(checktype == 'pt'){
//        $('#plaintextwarning').append('Please fill your question');
//        }
//        if(checktype=='ddl' ||checktype =='ddlans'){
//            
//        if(checktype=='ddl')
//        $('#ddlwarning').append('Please fill your question'); 
//        
//        if(checktype =='ddlans')
//        $('#addqtbuttonwarning').append('Please fill your answer'); 
//        
//        document.getElementById("addqtbutton").disabled= true;
//        }
//    }
//    else{
//    count = 0;
//    temp =0;
//    n = documentvalue.length;
//    for(i=0;i<n;i++){
//        if(documentvalue[i]==' '|| documentvalue[i]=='\n'){
//            count++;
//        }
//        if(documentvalue[i]=='#')
//        temp++;
//    }
//
//    //Check # character
//    if(checktype=='ddlans'){
//    if(temp !=0){
//    document.getElementById("addqtbutton").disabled= true;
//    $('#addqtbuttonwarning').append('You cannot using # in your answer');
//    }
//    }
//    
//    //Check only space and enter line
//    if(count == n){
//        
//        document.getElementById("id_submitbutton").disabled= true;
//        if(checktype == 'pt')
//        $('#plaintextwarning').append('You cannot fill only space or enter');
//        
//        if(checktype=='ddl' || checktype=='ddlans'){
//            if(checktype=='ddl')
//            $('#ddlwarning').append('You cannot fill only space or enter');   
//
//            if(checktype=='ddlans')
//            $('#addqtbuttonwarning').append('You cannot fill only space or enter');
//            
//            document.getElementById("addqtbutton").disabled= true;
//        }
//    }
//    }
    //dropdownlist check

// Statistic management
function showSurveyTable(survey_id)
{
    
    if(survey_id != '0')
    {
    $('#emailmessage').show();
    $('#surveytable').show();
    $('#initialsurveytable').show();
    $('#surveytablestatus').show();
    $('#selectstatus').show();
	$('#id_status').val('0'); // set default for status when change the survey
    $('#id_id_survey').val(survey_id);
    $('#surveytable').html("<table class=generalbox border=1 align=center style=\"margin-left:16%;\"><tr><td><h1>PROCESSING</h1></td></tr></table>");

	$.ajax({
		  type: 'GET',
		  url: "../ajax_statistic.php?tim=showstatisticsurvey&survey_id="+survey_id +"&status_id=123"+"&emailstring=123",
		  data:'',
		  dataType: 'html',
		  success: function(msg){
			  $('#surveytable').html(msg);
		  },
	});
    }
    else
    {
	$('#id_status').val('0');// set default for status when change the survey
    $('#emailmessage').hide();
    $('#surveytable').hide();
    $('#initialsurveytable').hide();
    $('#surveytablestatus').hide();
    $('#selectstatus').hide();
    }
    
} 
function showSurveyTableByStatus(status_id,survey_id)
{
    // Set null for field text
    $('#id_email_teacher').val('');
    $('#id_subject_teacher').val('');
	$.ajax({
		  type: 'GET',
		  url: "../ajax_statistic.php?tim=showstatisticbystatus&survey_id="+survey_id+"&status_id="+status_id+"&emailstring=123",
		  data:'',
		  dataType: 'html',
		  success: function(msg){
			  $('#surveytablestatus').html(msg);
		  },
	});
    
}
function sendMail() {
    alert('Ok1');
    var link = "mailto:0959025@itec.hcmus.edu.vn"
             + "?cc=myCCaddress@example.com"
             + "&subject=" + escape("Survey Notification")
             + "&body=" + escape('You have a survey');

    window.location.href = link;
    alert('Ok');
}
function setemail(checkbox_id,subject_id)
{
 email = document.getElementById(checkbox_id);
 temp = $('#id_email_teacher').val();
 temp2 =$('#id_subject_teacher').val();
 
 if(email.checked == true)
 {
 var string_email = ','+ email.value+'//'+subject_id+',';
 temp = temp + string_email;
 $('#id_email_teacher').val(temp);
 var subject_teacher = ',' + checkbox_id +',';
 temp2 = temp2 +subject_teacher;
 $('#id_subject_teacher').val(temp2);
 }
 else if(email.checked == false)
 {
    var str_replace = ','+ email.value + '//' + subject_id + ',';
    var xxx = temp.replace(str_replace,'');
    $('#id_email_teacher').val(xxx);
    
    var subject_teacher = ',' + checkbox_id +',';
    var xxx = temp2.replace(subject_teacher,'');
    $('#id_subject_teacher').val(xxx);
 }
}
function showemail(survey_id)
{
 temp = $('#id_email_teacher').val();
// email = new Array();
// email = temp.split(',,');
// for(i=0;i<email.length;i++)
// {
//    email[i]= email[i].replace(',','');
//    temp = new Array();
//    temp= email[i].split('//');
//    email[i] = temp[0];
//    alert(email[i]);
// }
if(temp.length > 0){
 subject = $('#id_email_subject').val();
 content = $('#id_email_content').val();
 var email = new Email(subject, content);
 	$.ajax({
		  type: 'POST',
		  url: "../ajax_statistic.php?tim=showemailteacher&survey_id="+survey_id +"&emailstring="+temp+"&status_id=123",
		  data:email,
		  dataType: 'html',
		  success: function(msg){
		      alert(msg);
			  //$('#emailteacher').html(msg);
		  },
	});   
}else{
    alert("No Recipient");
}
 
 $('#id_email_teacher').val("");
}
function checkallemail(checkboxstring,emailteacher)
{

checkall = document.getElementById('checkall');
if(checkall.checked == true){

 checkbox = new Array();
 checkbox = checkboxstring.split(',,');
 for(i=0;i<checkbox.length;i++)
 {
    checkbox[i] = checkbox[i].replace(',','');
    email = document.getElementById(checkbox[i]); 
    email.checked = true;
 } 
 $('#id_email_teacher').val('');
 $('#id_subject_teacher').val('');
 
 $('#id_email_teacher').val(emailteacher);
 $('#id_subject_teacher').val(checkboxstring);
}
else if(checkall.checked == false){
 checkbox = new Array();
 checkbox = checkboxstring.split(',,');
 for(i=0;i<checkbox.length;i++)
 {
    checkbox[i] = checkbox[i].replace(',','');
    email = document.getElementById(checkbox[i]); 
    email.checked = false;
 } 
 $('#id_email_teacher').val('');
 $('#id_subject_teacher').val('');  
}
}

//Benchmark Management
function showSurveyBenchmark(survey_id){
    $("#loader").show();
    if(survey_id != "0"){
        $('#surveyBenchmark').show();
        $('#id_printBenchmarkBtn').show();
        $.ajax({
            type: 'GET',
            url: "../ajaxBenchmark.php?tim=surveyBenchmark&survey_id="+survey_id,
            data:'',
            dataType: 'html',
            success: function(msg){
              //$('#surveyBenchmark').contents().find('head').empty();
              $('#surveyBenchmark').contents().find('body').empty();
              //$('#surveyBenchmark').contents().find('head').appendChild('<script src="../module.js"></script>');
              //$('#surveyBenchmark').contents().find('head').appendChild('<script src="../js/jquery-1.8.3.min.js"></script>');              
              $('#surveyBenchmark').contents().find('body').append(msg);
              $('#loader').hide();
            },
    	});    
    }else{
        $('#surveyBenchmark').contents().find('body').empty();
        $('#surveyBenchmark').hide();
        $('#id_printBenchmarkBtn').hide();
        $('#loader').hide();
    }
       
}

function clearFilteringMatrix(){
    $("#surveyBenchmark").contents().find('td').each(function(index){
        if($(this).attr("bgcolor") == "#D16587" ||
        $(this).attr("bgcolor") == "#00FF00" ||
        $(this).attr("bgcolor") == "#FFFF00" ||
        $(this).attr("bgcolor") == "#00FFFF"){
            $(this).attr("bgcolor","white");    
        }
    });
    
    $("#surveyBenchmark").contents().find('#historyFilter').html("History Filter:<br/>");
}

function deleteFilter(idFilter){
    myIframeElements = $("#surveyBenchmark").contents();
    myIframeElements.find('#loader').show();
    
    //clear old applied filter
    $("#surveyBenchmark").contents().find('td').each(function(index){
        if($(this).attr("bgcolor") == "#D16587" ||
        $(this).attr("bgcolor") == "#00FF00" ||
        $(this).attr("bgcolor") == "#FFFF00" ||
        $(this).attr("bgcolor") == "#00FFFF"){
            $(this).attr("bgcolor","white");    
        }
    });
    
    //Clear history filter
    myIframeElements.find('#historyFilter').empty();
    
    idSurvey = $("#surveyBenchmark").contents().find('#cur_survey_id').val();
        $.ajax({
    		  type: 'GET',
    		  url: "../ajaxBenchmark.php?tim=deleteFilter&survey_id="+idSurvey+"&filter="+idFilter,
    		  data: "",
              async: false,
    		  dataType: 'html',
    		  success: function(msg){
                  myIframeElements.find('#historyFilter').append("History Filter:<br/>");
    		      myIframeElements.find('#historyFilter').append(msg);
                  myIframeElements.find('#loader').hide();
    		  },
	    });
}

function refreshFilters(){
    myIframeElements = $("#surveyBenchmark").contents();
    myIframeElements.find('#loader').show();
    
    //clear old applied filter
    $("#surveyBenchmark").contents().find('td').each(function(index){
        if($(this).attr("bgcolor") == "#D16587" ||
        $(this).attr("bgcolor") == "#00FF00" ||
        $(this).attr("bgcolor") == "#FFFF00" ||
        $(this).attr("bgcolor") == "#00FFFF"){
            $(this).attr("bgcolor","white");    
        }
    });
    
    if(myIframeElements.find('#cbx_filter_enabler:checked').size() <= 0){
        myIframeElements.find('#loader').hide();
    }
    myIframeElements.find('#cbx_filter_enabler:checked').each(function(){
        myIframeElements.find('#loader').show();
        valueOfCheckbox = $(this).val();
        arrayOfValues = valueOfCheckbox.split("/");
        
        colIOp = arrayOfValues[0];
        colQtyI = arrayOfValues[1];
        colConnection1 = arrayOfValues[2];
        colTOp = arrayOfValues[3];
        colQtyT = arrayOfValues[4];
        colConnection2 = arrayOfValues[5];
        colUOp = arrayOfValues[6];
        colQtyU = arrayOfValues[7];
        
        rowIOp = arrayOfValues[8];
        rowQtyI = arrayOfValues[9];
        rowConnection1 = arrayOfValues[10];
        rowTOp = arrayOfValues[11];
        rowQtyT = arrayOfValues[12];
        rowConnection2 = arrayOfValues[13];
        rowUOp = arrayOfValues[14];
        rowQtyU = arrayOfValues[15];
        
        fColorCol = arrayOfValues[16];
        fColorRow = arrayOfValues[17];
        
        var filter = new FilterOfBenchmark("", colIOp, colQtyI, colConnection1, colTOp, colQtyT, colConnection2, colUOp, colQtyU, rowIOp, rowQtyI, rowConnection1, rowTOp, rowQtyT, rowConnection2, rowUOp, rowQtyU, fColorCol, fColorRow);
        $.ajax({
    		  type: 'POST',
    		  url: "../ajaxBenchmark.php?tim=resfreshWarn&survey_id="+$("#surveyBenchmark").contents().find('#cur_survey_id').val(),
    		  data: filter,
              async: false,
    		  dataType: 'html',
    		  success: function(msg){
    		      outputs = msg.split('/');
                  
    		      if(outputs[0].length > 0){
    		          subjectStr = outputs[0];
                      if(subjectStr.lastIndexOf(",") > 0){
                        //subjectStr = subjectStr.substr(0,subjectStr.lastIndexOf(","));  
                      }
                      subjects = subjectStr.split(',');
                      $.each( subjects, function( key, value ) {
                            subId = "sub"+value;
                            $("#surveyBenchmark").contents().find('td[id|="'+subId+'"]').attr("bgcolor",fColorRow);
                        });
    		      }
                  
                  if(outputs[1].length > 0){
                      losStr = outputs[1];
                      if(losStr.lastIndexOf(",") > 0){
                        //losStr = losStr.substr(0,losStr.lastIndexOf(","));  
                      }
                      los = losStr.split(',');

                      $.each( los, function( key, value ) {
                            loId = "-lo"+value;
                            $("#surveyBenchmark").contents().find('td[id$="'+loId+'"]').attr("bgcolor",fColorCol);
                        });
    		      }
                  myIframeElements.find('#loader').hide();
    		  },
	    });
        
    });
}


function filteringMatrix(){
    
    myIframeElements = $("#surveyBenchmark").contents();
    myIframeElements.find('#loader').show();
        
    colIOp = myIframeElements.find('#colIoperator').val();
    colTOp = myIframeElements.find('#colToperator').val();
    colUOp = myIframeElements.find('#colUoperator').val();
    
    rowIOp = myIframeElements.find('#rowIoperator').val();
    rowTOp = myIframeElements.find('#rowToperator').val();
    rowUOp = myIframeElements.find('#rowUoperator').val();
    
    colConnection1 = myIframeElements.find('#colConnection1').val();
    colConnection2 = myIframeElements.find('#colConnection2').val();
    
    rowConnection1 = myIframeElements.find('#rowConnection1').val();
    rowConnection2 = myIframeElements.find('#rowConnection2').val();
    
    fColorCol = myIframeElements.find('#colorCol').val();
    fColorRow = myIframeElements.find('#colorRow').val();
    
    
    f_description = myIframeElements.find('#f_description').val();
    
    if(colIOp != 0){
        colQtyI = myIframeElements.find('#colIqty').val();
    }else{
        colQtyI = 0;
    }
    
    if(colTOp != 0){
        colQtyT = myIframeElements.find('#colTqty').val();
    }else{
        colQtyT = 0;
    }
    
    
    if(colUOp != 0){
        colQtyU = myIframeElements.find('#colUqty').val();
    }else{
        colQtyU = 0;
    }
    
    
    if(rowIOp != 0){
        rowQtyI = myIframeElements.find('#rowIqty').val();
    }else{
        rowQtyI = 0;
    }
    
    
    if(rowTOp != 0){
        rowQtyT = myIframeElements.find('#rowTqty').val();
    }else{
        rowQtyT = 0;
    }
    
    
    if(rowUOp != 0){
        rowQtyU = myIframeElements.find('#rowUqty').val();
    }else{
        rowQtyU = 0;
    }
    
    paramForToggleFilterMethod = 
                    colIOp+"/"+
                    colQtyI+"/"+
                    colConnection1+"/"+
                    colTOp+"/"+
                    colQtyT+"/"+
                    colConnection2+"/"+
                    colUOp+"/"+
                    colQtyU+"/"+
                    rowIOp+"/"+
                    rowQtyI+"/"+
                    rowConnection1+"/"+
                    rowTOp+"/"+
                    rowQtyT+"/"+
                    rowConnection2+"/"+
                    rowUOp+"/"+
                    rowQtyU+"/"+
                    fColorCol+"/"+
                    fColorRow;
    
    colFilter = "";
    if(colIOp != 0){
        colFilter += "I "+colIOp+" "+colQtyI;    
        if(colTOp != 0){
            colFilter += colConnection1 +" T "+colTOp+" "+colQtyT;
            if (colUOp != 0)
                colFilter += colConnection2 +" U "+colUOp+" "+colQtyU;
        }else if(colUOp != 0){
            colFilter += colConnection2 +" U "+colUOp+" "+colQtyU;
        }
    }
    else if(colTOp != 0){
        colFilter += " T "+colTOp+" "+colQtyT;
        if(colUOp != 0){
            colFilter += colConnection2 +" U "+colUOp+" "+colQtyU;    
        }
    }else if(colUOp != 0){
        colFilter += " U "+colUOp+" "+colQtyU;
    }
    
    rowFilter = "";
    if(rowIOp != 0){
        rowFilter += "I "+rowIOp+" "+rowQtyI;    
        if(rowTOp != 0){
            rowFilter += rowConnection1 +" T "+rowTOp+" "+rowQtyT;
            if (rowUOp != 0)
                rowFilter += rowConnection2 +" U "+rowUOp+" "+rowQtyU;
        }else if(rowUOp != 0){
            rowFilter += rowConnection2 +" U "+rowUOp+" "+rowQtyU;
        }
    }
    else if(rowTOp != 0){
        rowFilter += " T "+rowTOp+" "+rowQtyT;
        if(rowUOp != 0){
            rowFilter += rowConnection2 +" U "+rowUOp+" "+rowQtyU;    
        }
    }else if(rowUOp != 0){
        rowFilter += " U "+rowUOp+" "+rowQtyU;
    }
    
    var filter = new FilterOfBenchmark(f_description, colIOp, colQtyI, colConnection1, colTOp, colQtyT, colConnection2, colUOp, colQtyU, rowIOp, rowQtyI, rowConnection1, rowTOp, rowQtyT, rowConnection2, rowUOp, rowQtyU, fColorCol, fColorRow);
        $.ajax({
    		  type: 'POST',
    		  url: "../ajaxBenchmark.php?tim=warn&survey_id="+$("#surveyBenchmark").contents().find('#cur_survey_id').val(),
    		  data: filter,
    		  dataType: 'html',
    		  success: function(msg){
    		      outputs = msg.split('/');
                  
                    myIframeElements.find('#historyFilter').append(f_description);
                    myIframeElements.find('#historyFilter').append("<input checked=\"checked\" type=\"checkbox\" name=\"cbx_filter_enabler\" id=\"cbx_filter_enabler\" onchange=\"parent.refreshFilters();\" value=\""+paramForToggleFilterMethod+"\" />");
                    myIframeElements.find('#historyFilter').append("<a href=\"#\" onclick=\"parent.deleteFilter("+outputs[2]+");return false;\">X</a>");
                    myIframeElements.find('#historyFilter').append("<div style=\"width:200px; background-color:"+myIframeElements.find('#colorCol').val()+";\">"+colFilter+"</div>");
                    myIframeElements.find('#historyFilter').append("<div style=\"width:200px;background-color:"+myIframeElements.find('#colorRow').val()+";\">"+rowFilter+"</div>");
                    myIframeElements.find('#historyFilter').append("-----------------END-----------------<br/>");
                  
    		      if(outputs[0].length > 0){
    		          subjectStr = outputs[0];
                      if(subjectStr.lastIndexOf(",") > 0){
                        //subjectStr = subjectStr.substr(0,subjectStr.lastIndexOf(","));  
                      }
                      subjects = subjectStr.split(',');
                      $.each( subjects, function( key, value ) {
                            subId = "sub"+value;
                            $("#surveyBenchmark").contents().find('td[id|="'+subId+'"]').attr("bgcolor",$("#surveyBenchmark").contents().find('#colorRow').val());
                        });
    		      }
                  
                  if(outputs[1].length > 0){
                      losStr = outputs[1];
                      if(losStr.lastIndexOf(",") > 0){
                        //losStr = losStr.substr(0,losStr.lastIndexOf(","));  
                      }
                      los = losStr.split(',');

                      $.each( los, function( key, value ) {
                            loId = "-lo"+value;
                            $("#surveyBenchmark").contents().find('td[id$="'+loId+'"]').attr("bgcolor",$("#surveyBenchmark").contents().find('#colorCol').val());
                        });
    		      }
                    myIframeElements.find('#loader').hide();
    		  },
	    });
}

function toggleMajorBlock(major_id){
    $.each($("#surveyBenchmark").contents().find('tr[id$="major-'+major_id+'"]'),function(key,value){
        $(this).toggle();
    });
}


//Initialize the jquery modal to display the instructors who checked the ITU Value of subject-lo in survey
//Use in benchmark.php
function intializeTooltip(){
        $("#dialog_instructor").dialog({
        	autoOpen: false,
        	height: 300,
        	width: 400,
        	modal: true,
            position: { my: "left top", at: "left bottom", of: window },            
            close: function() {
             $( this ).dialog( "close" );    
            }
        });
}

function displayInstructorOfITUValue(divInstructor){
    $("#dialog_instructor").dialog({ position:{ my:'left top',at:'left bottom',of:divInstructor}}); 
    //title = list of instructors (instructor list transfer to modal via attribute title)
    $('#instructorNames').html(divInstructor.title); 
    $("#dialog_instructor").dialog("open");
}

function reviewSurvey(subjectid, surveyid, instructorid, lo_id){
    //console.log(subjectid+ surveyid+ instructorid);
    var reviewRequest = new ReviewSurveyRequest(subjectid, surveyid, instructorid);
    
        var w = window.open("reviewSurvey.php");
        w.document.writeln('<script src="../js/jquery-1.8.3.min.js"></script>');
        //w.document.writeln('<script src="../js/jquery.scrollTo-1.4.3.1-min.js"></script>');
        w.document.writeln("<div id=\"loading\"><center><image src='../css/images/ajax-loader.gif'/></center></div>");
        
        //var curKey = $("input[name='sesskey']").val();
         
        $.ajax({
    		  type: 'POST',
    		  url: "reviewSurvey.php",
    		  data: reviewRequest,
    		  dataType: 'html',
    		  success: function(msg){
                    w.document.writeln("<script>$('#loading').html('');</script>");
                                        
                    
                    w.document.writeln(msg);
                    
                    $(w.document).find("div[id*='child_lo_block_']").hide();
                    $(w.document).find("input:checked[name*='ituCheckbox_']").each(function(index){
                        $(this).parents("div[id*='child_lo_block_']").each(function(index){
                            $(this).show();
                        });
                    });
                    //alert(lo_id);
                    
                    //way 1
                    //http://flesler.blogspot.com/2007/10/jqueryscrollto.html
                    //$(w).scrollTo($(w.document).find('#ituCheckbox_'+lo_id));
                    
                    //way 2
                    //anchor = $(w.document).find("a[href='anchor_"+lo_id+"']");
                    //offset = anchor.offset();
                    //alert(offset.top);
                    //$(w.document).scrollTop(offset.top);
                    var anchorLo = $(w.document).find("#"+lo_id); 
                    anchorLo.css("background-color","yellow");
                    
                    w.scrollTo(0,w.document.getElementById(lo_id).offsetTop);
            },
	    }); 
}


        
 function ExportToExcel()
    {
        //matrixTable
        htmltable = $('#surveyBenchmark').contents().find("#matrixTable").html();
       
       htmltable = "<html><body><table border = 1>" + htmltable;
       htmltable +=  "</table></body></html>";
       
      
       $('#id_benckmarktext').val(htmltable);

// MS OFFICE 2003  : data:application/vnd.ms-excel
// MS OFFICE 2007  : application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
        
        //window.open('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,' + encodeURIComponent(htmltable));
        
 
            var mapForm = document.createElement("form");
                mapForm.target = "Map";
                mapForm.method = "POST"; // or "post" if appropriate
                mapForm.action = "./print.php";
            
                var mapInput = document.createElement("input");
                mapInput.type = "text";
                mapInput.name = "content";
                mapInput.value = htmltable;
                mapForm.appendChild(mapInput);
            
                document.body.appendChild(mapForm);
            
                map = window.open("", "Map", "status=0,title=0,height=600,width=800,scrollbars=1");
            
            if (map) {
                mapForm.submit();
            } else {
                alert('You must allow popups for this map to work.');
		}
}
/******************************************************************************************************************************************************/
/*SUPPORT FUNCTION*/
function Preview_Survey(title, program, majors, questions, depthLO, expireDate, titleSum, Sum, titleQuestionSum, QuestionSum, titleLOSum, LOSum, curKey) {
        this.title = title;
        this.program = program;
        this.majors = majors;
        this.questions = questions;
        this.depthLO = depthLO;
        this.expireDate = expireDate;
        this.titleSum = titleSum;
        this.Sum = Sum;
        this.titleQuestionSum = titleQuestionSum;
        this.QuestionSum = QuestionSum;
        this.titleLOSum = titleLOSum;
        this.LOSum = LOSum;
        this.curKey = curKey;
}

function AssessAndTeach(sts,lo,content){
        this.sts_id = sts;
        this.lo_id = lo;
        this.content = content;
}

function ITUValue(sts,lo,content,typeOfValue){
        this.sts_id = sts;
        this.lo_id = lo;
        this.content = content;
        this.typeOfValue = typeOfValue;
}

function AnswerOfQuestion(sts_id,question_id,input,typeOfQuestion){
        this.sts_id = sts_id;
        this.question_id = question_id;
        this.input = input;
        this.typeOfQuestion = typeOfQuestion;
}

function Email(subject, content){
        this.subject = subject;
        this.content = content;
}

function FilterOfBenchmark(f_description, colIOp, colQtyI, colConnectionOne, colTOp, colQtyT, colConnectionTwo, colUOp, colQtyU, rowIOp, rowQtyI, rowConnectionOne, rowTOp, rowQtyT, rowConnectionTwo, rowUOp, rowQtyU, fColorCol, fColorRow){
    this.f_description =  f_description;
    this.colIOp =  colIOp;
    this.colQtyI = colQtyI;
    this.colConnection1 = colConnectionOne;
    this.colTOp = colTOp;
    this.colQtyT = colQtyT;
    this.colConnection2 = colConnectionTwo;
    this.colUOp = colUOp;
    this.colQtyU = colQtyU;
    this.rowIOp = rowIOp;
    this.rowQtyI = rowQtyI;
    this.rowConnection1 = rowConnectionOne;
    this.rowTOp = rowTOp;
    this.rowQtyT = rowQtyT;
    this.rowConnection2 =rowConnectionTwo;
    this.rowUOp = rowUOp;
    this.rowQtyU = rowQtyU;
    this.fColorCol = fColorCol;
    this.fColorRow = fColorRow;
}

function ReviewSurveyRequest(subject,survey,instructor){
    this.subject = subject;
    this.survey = survey;
    this.instructor = instructor;
}

function PrintableBenchmark(content){
    this.content = content;
}

function ExcelBenchmark(content){
    this.content = content;
}

function getCheckboxValue(destinationField, selectedElements){
    var storage = document.getElementById(destinationField);
    var str = "";
    var queryString = 'input:checkbox[name="'+selectedElements+'"]:checked';
    $(queryString).each(function() {
       str += this.value + ",";
    });
    str=str.substr(0,str.lastIndexOf(","));
    storage.value = str;
}

//Get value of ul list of selected question and put to hidden field
function getValueOfUnorderedList(destinationField, sourceList){
    var str = "";
    var storage = document.getElementById(destinationField);
    var queryString = '#' + sourceList;
    
    $.each($(queryString).children(),function(){
            str += $(this).attr('value') + ",";
        }
    );
    str=str.substr(0,str.lastIndexOf(","));
    storage.value = str;
}

function redirectTo(url){
    window.location.assign(url);
}

function controlDigitNumberInDiv(divName,action,step){
    var strStorage = divName;
    var storage = document.getElementById(strStorage);
    var curVal = parseInt(storage.value);
    if(action == "+"){
        curVal = curVal + parseInt(step);
    }
    if(action == "-"){
        if(curVal != 0){
            curVal = curVal - parseInt(step);    
        }
    }
    storage.value = curVal;
}

function setDefaultValueToDateTimeSelectoMoodle(mysqlDateTime,idOfDateTimeSelector){    
    var date = mysqlDateTime.substring(0, mysqlDateTime.indexOf(" "));
    var time = mysqlDateTime.substring(mysqlDateTime.indexOf(" ")+1);
    var dateArray = date.split("-");
    var timeArray = time.split(":");
    
    
    var selectorDay = "#"+idOfDateTimeSelector+"_day";
    var selectorMonth = "#"+idOfDateTimeSelector+"_month";
    var selectorYear ="#"+idOfDateTimeSelector+"_year";
    var selectorHour = "#"+idOfDateTimeSelector+"_hour";
    var selectorMinute = "#"+idOfDateTimeSelector+"_minute";
    
    $(selectorDay).val(dateArray[2]);
    $(selectorMonth).val(parseInt(dateArray[1]));
    $(selectorYear).val(dateArray[0]);
    
    var hour = timeArray[0];
    
    if(hour.indexOf("0") >= 0){
         hour = hour.substring(1);
    }
    $(selectorHour).val(hour);
    
    var minute = timeArray[1];
    $(selectorMinute).val((Math.round((parseInt(minute)/60)*10)+1)*5); 
}

